// 获取音频元素和按钮
const bgm = document.getElementById('bgm');
const toggleBtn = document.getElementById('bgmToggle');

// 设置初始音量
bgm.volume = 0.5;

// 恢复播放状态
window.addEventListener('load', () => {
  const storedTime = sessionStorage.getItem('bgmTime');
  const isMuted = sessionStorage.getItem('bgmMuted') === 'true';

  if (storedTime) {
    bgm.currentTime = parseFloat(storedTime);
  }

  bgm.muted = isMuted;
  toggleBtn.textContent = isMuted ? '🔇' : '🔊';

  // 微信和浏览器兼容：首次用户交互时播放音乐
  function tryPlayAudio() {
    bgm.play().then(() => {
      console.log("背景音乐已播放");
    }).catch(() => {
      console.log("等待用户交互");
    });
  }

  document.addEventListener('WeixinJSBridgeReady', tryPlayAudio);
  document.addEventListener('touchstart', tryPlayAudio, { once: true });
  document.addEventListener('click', tryPlayAudio, { once: true });
// 添加预加载和自动重试逻辑
//   bgm.load();
//   const playWithRetry = () => {
//     bgm.play().catch(e => {
//       console.log('播放失败，1秒后重试');
//       setTimeout(playWithRetry, 1000);
//     });
//   };

//   // 微信浏览器特殊处理
//   if (/MicroMessenger/i.test(navigator.userAgent)) {
//     document.addEventListener('WeixinJSBridgeReady', playWithRetry, false);
//   } else {
//     playWithRetry();
//   }
//   bgm.play().catch(() => {});
//   document.body.addEventListener('click', function firstInteraction() {
//     bgm.play().catch(() => {});
//   document.body.removeEventListener('click', firstInteraction);
//   });
});

// 保存播放状态
window.addEventListener('beforeunload', () => {
  sessionStorage.setItem('bgmTime', bgm.currentTime);
  sessionStorage.setItem('bgmMuted', bgm.muted);
});

// 切换静音状态
toggleBtn.addEventListener('click', () => {
  bgm.muted = !bgm.muted;
  toggleBtn.textContent = bgm.muted ? '🔇' : '🔊';
});

const container = document.querySelector('.balloon-container');

  function createBalloon() {
    const balloon = document.createElement('div');
    balloon.classList.add('balloon');
    balloon.style.left = Math.random() * 100 + 'vw';
    balloon.style.animationDuration = (6 + Math.random() * 5) + 's';
    container.appendChild(balloon);

    setTimeout(() => {
      balloon.remove();
    }, 12000);
  }

  setInterval(createBalloon, 1800);

// 添加缓冲事件监听
bgm.addEventListener('stalled', () => {
  console.log('网络中断，尝试重新加载');
  bgm.load();
  bgm.play().catch(() => {});
});

bgm.addEventListener('error', () => {
  console.log('音频加载错误，尝试重新加载');
  setTimeout(() => {
    bgm.load();
    bgm.play().catch(() => {});
  }, 1000);
});